<template>
    <div class="qilin-qualificationDialog">
        <el-dialog
            :visible.sync="ownDialogConfig.isShow" :title="ownDialogConfig.title"
            width="600px" center append-to-body :before-close="handleClose"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-form ref="formData" :model="formData" :rules="formRule" size="mini"
                label-width="100px" label-position="right" label-suffix=":" class="upload-form"
            >
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="部门" prop="employeeDepartment">
                            <el-select placeholder="请选择" v-model="formData.employeeDepartment"
                                clearable @change="changeEmployeeDepartment"
                                :disabled="!!formData.certificationId"
                            >
                                <el-option v-for="item in employeeDepartmentList" :key="item.id"
                                    :label="item.label" :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="employeeName">
                            <el-select placeholder="请选择姓名" v-model="formData.employeeName" clearable
                                filterable :disabled="!!formData.certificationId"
                            >
                                <el-option v-for="item in employeeNameList" :key="item.id"
                                    :label="`${item.label}(${item.code})`" :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="证书名称" prop="certificateName">
                            <el-input type="text" placeholder="请输入" v-model="formData.certificateName"
                                clearable
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="证书有效期" prop="certificateIndate">
                            <el-date-picker type="date" placeholder="请选择日期"
                                v-model="formData.certificateIndate" class="date"
                                format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
                        <el-form-item label="年份" prop="year">
                            <el-date-picker type="year" placeholder="请选择年份"
                                v-model="formData.year" class="date"
                                format="yyyy" value-format="yyyy"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="12">
                        <el-form-item label="资质等级" prop="certificationGrade">
                            <el-select placeholder="请选择" v-model="formData.certificationGrade" clearable
                                @change="changeQualificationsLevel"
                            >
                                <el-option v-for="item in qualificationsLevelList" :key="item.value"
                                    :label="item.label" :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="资质积分" prop="certificationIntegral">
                            <el-select placeholder="请选择" v-model="formData.certificationIntegral" disabled>
                                <el-option v-for="item in qualificationsScoreList" :key="item.value"
                                    :label="item.label" :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input type="textarea" v-model="formData.remark" :rows="3"
                                placeholder="请输入"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="附件上传" prop="files">
                            <el-upload action="#" list-type="picture-card" ref="upload"
                                :show-file-list="true" :key="num"
                                :limit="6" :auto-upload="false"
                                accept=".jpg,.jpeg,.png,.gif"
                                :file-list="fileList"
                                :before-upload="beforeUpload"
                                :on-change="changeUpload"
                                :on-preview="previewUpload"
                                :on-remove="removeUpload"
                                :on-exceed="exceedUpload"
                            >
                                <i slot="default" class="el-icon-camera-solid"></i>
                                <div class="upload-tip" slot="tip">最多6张，单个图片不超过20M</div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer">
                <el-button type="default" size="mini" @click="handleClose">取消</el-button>
                <el-button type="primary" size="mini" @click="submitData('formData')">确认</el-button>
            </div>
        </el-dialog>
        <el-dialog :visible.sync="dialogImage.isShow" title="" :append-to-body="true" center>
            <img width="100%" height="400px" :src="dialogImage.imgSrc" alt="">
            <div class="Qilin-image-pagination">
                <i class="el-icon-caret-left" @click="prev()"></i>
                <div class="Qilin-image-pagination-page">
                    <span>{{dialogImage.currentIndex}}</span>
                    <span>/</span>
                    <span>{{dialogImage.total}}</span>
                </div>
                <i class="el-icon-caret-right" @click="next()"></i>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import {insertQualificationsData,getEmployeeData} from "@/api/index.js";
import {uploadImageUrl} from "@/setting.js";
export default {
    data(){
        return {
            ownDialogConfig:{ //弹窗自身的配置
                isShow:false,
                title:"新增"
            },
            formData:{ // 弹窗内表单配置
                employeeCode:"",
                employeeName:"",
                employeeDepartment:"",
                certificateName:"",
                certificateIndate:"",
                year:"",
                certificationGrade:"",
                certificationIntegral:"",
                files:"",
                remark:""
            },
            formRule:{ //弹窗内表单校验规则配置
                employeeDepartment:[
                    {
                        required:true,
                        message:"请选择部门",
                        trigger:"change"
                    }
                ],
                employeeName:[
                    {
                        required:true,
                        message:"请选择姓名",
                        trigger:"change"
                    }
                ],
                certificateName:[
                    {
                        required:true,
                        message:"请输入证书名称",
                        trigger:"blur"
                    }
                ],
                year:[
                    {
                        required:true,
                        message:"请输入年份",
                        trigger:"blur"
                    }
                ],
                certificationGrade:[
                    {
                        required:true,
                        message:"请选择资质等级",
                        trigger:"change"
                    }
                ],
                certificationIntegral:[
                    {
                        required:true,
                        message:"请选择资质积分",
                        trigger:"change"
                    }
                ]
            },
            qualificationsLevelList:[ //资质等级下拉数据集
                {
                    label:"A",
                    value:"A",
                    id:1
                },
                {
                    label:"B",
                    value:"B",
                    id:2
                },
                {
                    label:"C",
                    value:"C",
                    id:3
                },
                {
                    label:"D",
                    value:"D",
                    id:4
                }
            ],
            qualificationsScoreList:[ //资质积分下拉数据集
                {
                    label:"30分",
                    value:30,
                    id:1
                },
                {
                    label:"15分",
                    value:15,
                    id:2
                },
                {
                    label:"10分",
                    value:10,
                    id:3
                },
                {
                    label:"2分",
                    value:2,
                    id:4
                }
            ],
            fileList:[], //已上传的文件列表
            dialogImage:{ // 选中上传图片后的图片查看弹窗
                isShow:false,
                imgSrc:"",
                currentIndex:1,
                total:1
            },
            num:0,
            employeeDepartmentList:[ // 部门下拉选择数据集
                {
                    label:"综合部",
                    value:"综合部",
                    id:1
                },
                {
                    label:"财务部",
                    value:"财务部",
                    id:2
                },
                {
                    label:"市场拓展部",
                    value:"市场拓展部",
                    id:3
                },
                {
                    label:"系统集成部",
                    value:"系统集成部",
                    id:4
                },
                {
                    label:"工程部",
                    value:"工程部",
                    id:5
                },
                {
                    label:"产品研发部",
                    value:"产品研发部",
                    id:6
                },
                {
                    label:"平台运维部",
                    value:"平台运维部",
                    id:7
                }
            ],
            employeeNameList:[] //姓名下拉选择数据集
        }
    },
    methods:{
        // 修改时事件监听
        initUpdate(data){
            if(!data){ // 新增时进入
                this.ownDialogConfig.title="新增";
            }else{ //编辑时进入
                this.ownDialogConfig.title="编辑";
                this.formData={...data};
                this.formData.employeeName=this.formData.employeeId;
                if(this.formData.certificateIndate == "长期有效"){
                    this.formData.certificateIndate="";
                }
                this.formData.year=this.formData.year+"";
                this.formData.files=this.formData.attachments.map((item)=>{
                    return {
                        url:item.filePath,
                        attachmentId:item.attachmentId
                    };
                });
                this.fileList=this.formData.attachments.map((item)=>{
                    return {
                        url:uploadImageUrl+item.filePath,
                        attachmentId:item.attachmentId
                    };
                });
                this.getEmployeeData(this.formData.employeeDepartment);
            }
            this.ownDialogConfig.isShow=true;
        },
        // 初始化获取所在部门下人员信息事件监听
        getEmployeeData(departmentName){
            getEmployeeData({employeeDepartment:departmentName}).then((res)=>{
                if(res.code === 200){
                    this.employeeNameList=res.result.map((item)=>{
                        return {
                            id:item.employeeId,
                            label:item.employeeName,
                            value:item.employeeId,
                            code:item.employeeCode
                        }
                    });
                }
            });
        },
        // 当选择部门事件监听
        changeEmployeeDepartment(value){
            this.formData.employeeName="";
            this.$nextTick(()=>{
                this.$refs["formData"].clearValidate("employeeName");
            });
            if(!value){
                this.employeeNameList=[];
            }else{
                this.getEmployeeData(value);
            }
        },
        // 当选择资质等级事件监听
        changeQualificationsLevel(value){
            if(!value){
                this.formData.certificationIntegral="";
            }else{
                const selectId=this.qualificationsLevelList.find((item)=>{return item.value == value}).id;
                const finalValue=this.qualificationsScoreList.find((item)=>{return item.id == selectId}).value;
                this.formData.certificationIntegral=finalValue;
            }
        },
        // 上传文件之前的事件监听--当auto-upload为false不触发该钩子
        beforeUpload(file){
            console.log("beforeUpload",file);
        },
        // 文件状态改变时的事件监听
        changeUpload(file){
            // console.log(file);
            const imageType=file.name.split(".").pop();
            if(!["jpg","jpeg","png","gif"].includes(imageType)){
                this.$message({
                    message:"请上传图片格式的文件",
                    type:"warning"
                });
                this.$refs["upload"].uploadFiles.splice(0,1);
            }else if(file.size > 20 * 1000 * 1000){
                this.$message({
                    message:"图片大小不可超过20M",
                    type:"warning"
                });
                this.$refs["upload"].uploadFiles.splice(0,1);
            }else{
                this.fileList.push({
                    url:file.url,
                    raw:file.raw
                });
                this.formData.files=this.fileList;
            }
        },
        // 点击已上传文件预览时的事件监听
        previewUpload(file){
            // console.log("previewUpload",file);
            this.dialogImage.isShow=true;
            this.dialogImage.imgSrc=file.url;
            this.dialogImage.currentIndex=this.fileList.findIndex((item)=>{return item.url == file.url})+1;
            this.dialogImage.total=this.fileList.length;
        },
        // 移除已上传文件时的事件监听
        removeUpload(file){
            this.num++;
            const index=this.fileList.findIndex((item)=>{
                return item.url === file.url;
            });
            this.fileList.splice(index,1);
        },
        // 超出限制上传文件数量事件监听
        exceedUpload(){
            this.$message({
                message:"上传图片数量最多6张",
                type:"warning"
            });
        },
        // 点击预览上一张图片图标事件监听
        prev(){
            if(this.dialogImage.currentIndex !== 1){
                this.dialogImage.currentIndex--;
                this.dialogImage.imgSrc=this.fileList[this.dialogImage.currentIndex-1].url;
            }else{
                this.$message({
                    message:"已是第一张图片",
                    type:"warning"
                });
            }
        },
        // 点击预览下一章图片事件监听
        next(){
            if(this.dialogImage.currentIndex !== this.fileList.length){
                this.dialogImage.currentIndex++;
                this.dialogImage.imgSrc=this.fileList[this.dialogImage.currentIndex-1].url;
            }else{
                this.$message({
                    message:"已是最后一张图片",
                    type:"warning"
                });
            }
        },
        // 点击确认按钮事件监听
        submitData(refName){
            this.$refs[refName].validate((valid)=>{
                if(valid){
                    // console.log(this.formData);
                    let formData=new FormData();
                    // formData.append("employeeCode",this.formData.employeeCode);
                    // formData.append("employeeName",this.formData.employeeName);
                    // formData.append("employeeDepartment",this.formData.employeeDepartment);
                    formData.append("employeeId",this.formData.employeeName);
                    formData.append("certificateName",this.formData.certificateName);
                    formData.append("certificateIndate",this.formData.certificateIndate ?? "");
                    formData.append("certificationGrade",this.formData.certificationGrade);
                    formData.append("certificationIntegral",this.formData.certificationIntegral);
                    formData.append("remark",this.formData.remark);
                    if(this.formData["files"]){
                        this.formData["files"].forEach((item)=>{
                            if(item.raw){ //新增的图片附件
                                formData.append("files",item.raw);
                            }
                        });
                    }
                    // formData.append("year",this.formData.year);
                    formData.append("year",new Date().getFullYear());
                    if(!this.formData.certificationId){ //新增时进入
                        insertQualificationsData(formData).then((res)=>{
                            if(res.code === 200){
                                this.$message({
                                    message:"新增成功",
                                    type:"success"
                                });
                                this.$emit("refresh");
                                this.handleClose();
                            }else{
                                this.$message({
                                    message:res.message || "请求错误",
                                    type:"error"
                                });
                            }
                        });
                    }else{ // 编辑时进入
                        let attachmentIds=[];
                        this.fileList.forEach((item)=>{
                            if(item.attachmentId){
                                attachmentIds.push(item.attachmentId);
                            }
                        });
                        formData.append("attachmentIds",attachmentIds.join(","));
                        formData.append("certificationId",this.formData.certificationId);
                        insertQualificationsData(formData).then((res)=>{
                            if(res.code === 200){
                                this.$message({
                                    message:"编辑成功",
                                    type:"success"
                                });
                                this.$emit("refresh");
                                this.handleClose();
                            }else{
                                this.$message({
                                    message:res.message || "请求错误",
                                    type:"error"
                                });
                            }
                        });
                    }
                }
            });
        },
        // 关闭弹窗事件监听
        handleClose(){
            this.fileList=[];
            this.employeeNameList=[];
            this.$refs["upload"].clearFiles();
            this.$refs["formData"].resetFields();
            for(let key in this.formData){
                this.formData[key]="";
            }
            this.ownDialogConfig.isShow=false;
        }
    },
    mounted(){

    }
}
</script>
<style lang="scss" scoped>
.Qilin-image-pagination{
    @include flexCenter();
    margin-top: 10px;
    >i{
        font-size: 30px;
        color: $color-text-common;
        cursor:pointer;
    }
    >div.Qilin-image-pagination-page{
        background-color: #eaeaea;
        border-radius:2px;
        padding: 5px 20px;
        >span{
            margin:0 1px;
            &:first-child{
                color:$color-text-title;
            }
            &:nth-last-child(-n+2){
                color:$color-text-common;
            }
        }
    }
}
</style>
